import { Module } from '@nestjs/common';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { ThrottlerModule } from '@nestjs/throttler';
import { HelmetModule } from '@nestjs/helmet';
import { MulterModule } from '@nestjs/platform-express';
import { validateConfiguration } from './config/configuration';
import configuration from './config/configuration';
import { DatabaseModule } from './database/database.module';
import { AuthModule } from './auth/auth.module';
import { ScoringModule } from './modules/scoring/scoring.module';
import { HealthModule } from './health/health.module';
import { AuditModule } from './audit/audit.module';
import { LoggerModule } from './logger/logger.module';
import { AppExceptionFilter } from './common/filters/app-exception.filter';
import { ResponseInterceptor } from './common/interceptors/response.interceptor';
import { LoggingInterceptor } from './common/interceptors/logging.interceptor';
import { ValidationPipe } from '@nestjs/common';
import { APP_FILTER, APP_INTERCEPTOR, APP_PIPE } from '@nestjs/core';

@Module({
  imports: [
    // 配置模块 - 零容忍验证
    ConfigModule.forRoot({
      isGlobal: true,
      load: [configuration],
      validate: validateConfiguration, // 零容忍：配置验证失败立即终止
      validationOptions: {
        allowUnknown: true,
        abortEarly: true,
      },
      envFilePath: ['.env.production', '.env.local', '.env'],
    }),

    // 安全模块
    HelmetModule.forRoot({
      contentSecurityPolicy: {
        directives: {
          defaultSrc: ["'self'"],
          styleSrc: ["'self'", "'unsafe-inline'"],
          scriptSrc: ["'self'"],
          imgSrc: ["'self'", "data:", "https:"],
        },
      },
      hsts: {
        maxAge: 31536000,
        includeSubDomains: true,
        preload: true,
      },
    }),

    // 限流模块
    ThrottlerModule.forRootAsync({
      imports: [ConfigModule],
      useFactory: (configService: ConfigService) => ({
        throttlers: [
          {
            ttl: configService.get<number>('RATE_LIMIT_WINDOW', 60000),
            limit: configService.get<number>('RATE_LIMIT_MAX', 10),
          },
        ],
      }),
      inject: [ConfigService],
    }),

    // 文件上传模块
    MulterModule.registerAsync({
      imports: [ConfigModule],
      useFactory: (configService: ConfigService) => ({
        dest: configService.get<string>('UPLOAD_PATH'),
        limits: {
          fileSize: configService.get<number>('MAX_FILE_SIZE', 10 * 1024 * 1024),
          files: 1,
        },
        fileFilter: (req, file, cb) => {
          const allowedTypes = configService.get<string>('ALLOWED_FILE_TYPES', 'jpg,jpeg,png,tiff')
            .split(',')
            .map(type => type.trim());

          const fileExtension = file.originalname.toLowerCase().split('.').pop();

          if (allowedTypes.includes(fileExtension)) {
            cb(null, true);
          } else {
            cb(new Error(`不支持的文件类型: ${fileExtension}`), false);
          }
        },
      }),
      inject: [ConfigService],
    }),

    // 业务模块
    DatabaseModule,
    AuthModule,
    ScoringModule,
    HealthModule,
    AuditModule,
    LoggerModule,
  ],
  providers: [
    // 全局异常过滤器
    {
      provide: APP_FILTER,
      useClass: AppExceptionFilter,
    },
    // 全局响应拦截器
    {
      provide: APP_INTERCEPTOR,
      useClass: ResponseInterceptor,
    },
    // 全局日志拦截器
    {
      provide: APP_INTERCEPTOR,
      useClass: LoggingInterceptor,
    },
    // 全局验证管道
    {
      provide: APP_PIPE,
      useFactory: () => new ValidationPipe({
        whitelist: true, // 只保留DTO中定义的属性
        forbidNonWhitelisted: true, // 拒绝额外属性
        transform: true, // 自动转换类型
        transformOptions: {
          enableImplicitConversion: true,
        },
      }),
    },
  ],
})
export class AppModule {
  constructor(private readonly configService: ConfigService) {
    // 零容忍策略：应用启动时进行最终安全检查
    this.performSecurityChecks();
  }

  private performSecurityChecks(): void {
    console.log('🔒 执行启动安全检查...');

    // 检查关键环境变量
    const criticalConfigs = [
      'JWT_SECRET',
      'DATABASE_URL',
      'AI_INFERENCE_URL',
      'REDIS_HOST',
    ];

    for (const configKey of criticalConfigs) {
      const value = this.configService.get<string>(configKey);
      if (!value) {
        console.error(`🚨 CRITICAL: 缺少关键配置 ${configKey}`);
        process.exit(1);
      }
    }

    // 检查生产环境安全配置
    if (this.configService.get<string>('NODE_ENV') === 'production') {
      this.validateProductionSecurity();
    }

    console.log('✅ 安全检查通过，应用启动完成');
  }

  private validateProductionSecurity(): void {
    const securityChecks = [
      {
        condition: this.configService.get<string>('NODE_ENV') === 'production',
        message: '生产环境配置正确',
      },
      {
        condition: this.configService.get<number>('BCRYPT_ROUNDS') >= 12,
        message: 'bcrypt加密强度符合要求',
      },
      {
        condition: this.configService.get<number>('MAX_FILE_SIZE') <= 50 * 1024 * 1024,
        message: '文件大小限制安全',
      },
    ];

    for (const check of securityChecks) {
      if (!check.condition) {
        console.error(`🚨 CRITICAL: ${check.message}`);
        process.exit(1);
      }
    }

    console.log('✅ 生产环境安全验证通过');
  }
}